import PySide2
import pyqtgraph as pg
import cv2
import logging
import os
import anime, merge
import shutil
# log information settings
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')

dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path




from PySide2.QtWidgets import QApplication, QFileDialog
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QCoreApplication


class Stats:

    def __init__(self):
        # 从文件中加载UI定义

        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        self.ui = QUiLoader().load('main.ui')
        loader = QUiLoader()
        loader.registerCustomWidget(pg.PlotWidget)

        self.ui.cleanButton.clicked.connect(self.remove)
        self.ui.StartButton.clicked.connect(self.handdle)
        self.ui.quitButton.clicked.connect(QCoreApplication.quit)

    def remove(self):
        CleanDirectory,_ = QFileDialog.getExistingDirectory(self.ui, "删除文件夹")
        shutil.rmtree(CleanDirectory)
        print("清空完毕！")



    def handdle(self):
        InputVedioPath,_ = QFileDialog.getOpenFileName(self.ui, "选择视频文件", r"C:\\")

        # 2. 读取视频，获取视频的帧率参数
        cap = cv2.VideoCapture(InputVedioPath.__str__())

        # isOpened() -> retval
        # .   @brief Returns true if video capturing has been initialized already.
        isOpened = cap.isOpened()

        fps = int(cap.get(cv2.CAP_PROP_FPS))  # 帧率<每秒中展示多少张图片>


        images_path = QFileDialog.getExistingDirectory(self.ui, "选择视频分解存储路径")
        animation_figure = QFileDialog.getExistingDirectory(self.ui, "选择风格转化存储路径")

        i = 0
        while(isOpened):
            i = i + 1
            # read([, image]) -> retval, image
            # .   @brief Grabs, decodes and returns the next video frame.
            (flag, frame) = cap.read()  # 读取每一张 flag<读取是否成功> frame<内容>
            filename = 'image' + str(i) + '.jpg'
            if flag == True:  #读取成功的话
                cv2.imwrite(images_path + os.sep + filename,frame,[cv2.IMWRITE_JPEG_QUALITY,100])
                cartnoon_data = anime.caart(cv2.imread(images_path +"\\" + filename))
                cv2.imwrite(animation_figure + "\\" + "cartnoon" + filename,cartnoon_data)
                #写入文件，1 文件名 2 文件内容 3 质量设置
            else:
                break
        print("视频分解成功！")
        print("图片转化完毕!")
        shutil.rmtree(images_path)

        OutputVideoName, _  = QFileDialog.getSaveFileName(
            self.ui,             # 父窗口对象
            "图片合成视频", # 标题
            r"C:\\",        # 起始目录

        )

        merge.pic_to_video(animation_figure, OutputVideoName, fps)

        print("视频合成成功！")

        Video_Add_Audio, _  = QFileDialog.getSaveFileName(
            self.ui,             # 父窗口对象
            "视频添加音频", # 标题
            r"C:\\",        # 起始目录

        )

        merge.video_add_audio(InputVedioPath,animation_figure,OutputVideoName,fps,Video_Add_Audio)
        print("视频成功添加音频！")


app = QApplication([])
stats = Stats()
stats.ui.show()
app.exec_()
